package com.woniu.service.impl;

import com.woniu.constant.SystemConstant;
import com.woniu.dao.AuthDAO;
import com.woniu.pojo.Auth;
import com.woniu.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private AuthDAO authDAO;
    @Override
    public List<Auth> findAuthByUserId(Integer userId, Integer parentId) {
        return authDAO.queryAuthByUserId(userId,parentId);
    }

    @Override
    public List<Auth> findAll() {
        return authDAO.queryAll();
    }

    @Override
    public int saveAuth(Auth auth) {
        Auth auth1=authDAO.queryAuthByName(auth.getAuthName());
        if (auth1!=null){
            return -1;
        }
        authDAO.insertSelective(auth);
        //更新当前节点父节点的状态
        authDAO.updateState(SystemConstant.CLOSED_STATUS,auth.getParentId());
        return 1;
    }

    @Override
    public int updateAuth(Auth auth) {
       Auth auth1=authDAO.queryAuthByName(auth.getAuthName());
       if (auth1!=null){
           if (!auth1.getAuthId().equals(auth.getAuthId())){
               return -1;
           }
       }
       authDAO.updateByPrimaryKeySelective(auth);
       return 1;
    }

    @Override
    public int deleteAuth(Integer authId) {
        List<Auth>list=authDAO.queryAuthsByParentId(authId);
        if (list.size()>0){
            return -1;
        }
        Auth auth=authDAO.selectByPrimaryKey(authId);
        authDAO.deleteByPrimaryKey(authId);
        //判断当前节点的父节点下是否还存在其他节点，如果不存在节点则要更新父节点的状态为open
        List<Auth> children = authDAO.queryAuthsByParentId(auth.getParentId());
        if(children.size() == 0){
            authDAO.updateState(SystemConstant.OPEN_STATUS,auth.getParentId());
        }
        return 1;
    }
    }

